package logic

import (
	"context"
	"go-zero-demo-04/mall/user/rpc/model"
	"google.golang.org/grpc/status"

	"go-zero-demo-04/mall/user/rpc/internal/svc"
	"go-zero-demo-04/mall/user/rpc/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *user.RegisterRequest) (*user.RegisterResponse, error) {
	_, err := l.svcCtx.StudentModel.FindOne(l.ctx, in.StudentID)
	if err == nil {
		return nil, status.Error(100, "该学号已存在")
	}

	if err == model.ErrNotFound {

		newStudent := model.Student{
			CollegeName:    in.CollegeName,
			Departmentname: in.DepartmentName,
			ClassNo:        in.ClassID,
			StudentNo:      in.StudentID,
			StudentName:    in.StudentName,
			StudentAge:     in.Age,
			StudentSex:     in.Sex,
			Password:       in.Password,
		}

		_, err := l.svcCtx.StudentModel.Insert(l.ctx, &newStudent)
		if err != nil {
			return nil, status.Error(500, err.Error())
		}

		//newStudent.StudentNo, err = res.
		//if err != nil {
		// return nil, status.Error(500, err.Error())
		//}

		return &user.RegisterResponse{
			Result: "注册成功",
		}, nil

	}

	return nil, status.Error(500, err.Error())
}
